import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class IpCache {


    static Cache<Integer, InetAddress> ipCache = CacheBuilder.newBuilder()
            .maximumSize(1000) // 设置缓存最大容量
            .expireAfterWrite(3, TimeUnit.MINUTES) // 设置写入后的过期时间
            .build();


    private static byte[] initIp = new byte[]{(byte)172,(byte)29,(byte)1,(byte) 3};
    private static AtomicInteger number = new AtomicInteger(0);


    public static int generateIp(){
        return bytesToInt(initIp)+number.getAndIncrement();
    }

    private static int bytesToInt(byte[] bytes) {
        if (bytes.length != 4) {
            throw new IllegalArgumentException("Byte array must have length of 4");
        }
        int result = 0;
        for (int i = 0; i < 4; i++) {
            result = (result << 8) | (bytes[i] & 0xFF);
        }
        return result;
    }

    private static byte[] intToBytes(int value) {
        byte[] bytes = new byte[4];
        bytes[0] = (byte) ((value >> 24) & 0xFF);
        bytes[1] = (byte) ((value >> 16) & 0xFF);
        bytes[2] = (byte) ((value >> 8) & 0xFF);
        bytes[3] = (byte) (value & 0xFF);
        return bytes;
    }


    public static byte[] putCache(InetAddress inetAddress){
        int i = generateIp();
        ipCache.put(i,inetAddress);
        return intToBytes(i);
    }

    public static InetAddress getCache(InetAddress inetAddress){
        byte[] address = inetAddress.getAddress();
        return ipCache.getIfPresent(bytesToInt(address));
    }

}
